package com.richapp.launcher.ui.activities;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.http.IpHttpService;
import com.http.RetrofitFactory;
import com.lsjwzh.widget.recyclerviewpager.LoopRecyclerViewPager;
import com.richapp.launcher.BuildConfig;
import com.richapp.launcher.R;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.mode.DeviceModel;
import com.richapp.launcher.net.mobile.server.UserServer;
import com.richapp.launcher.receiver.AlarmReceiver;
import com.richapp.launcher.receiver.LauncherMessageReceiver;
import com.richapp.launcher.serialport.gateway.command.AddCmd;
import com.richapp.launcher.ui.model.IpLocationModel;
import com.richapp.launcher.ui.model.PmModel;
import com.richapp.launcher.ui.model.WeatherModel;
import com.richapp.launcher.ui.view.MyPlatformGridView;
import com.richapp.launcher.ui.view.SimplePop;
import com.richapp.launcher.utils.BizUtils;
import com.richapp.launcher.utils.Constants;
import com.richapp.launcher.utils.ServiceUtil;
import com.richapp.launcher.utils.SharePrefenceUtil;
import com.richapp.launcher.utils.Tools;
import com.rxutil.RxJavaHelper;
import com.rxutil.RxSbuscriber;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Observable;
import rx.functions.Func1;


/**
 * Created by wangwei on 2017/4/7.
 */

public class StartActivity extends Activity implements View.OnClickListener {
    private static final String TAG = StartActivity.class.getSimpleName();
    private int interval=1000*60*60*24;
    private List<List<DeviceModel>> deviceList = new ArrayList();
    private LoopRecyclerViewPager pager;
    private TextView address;
    private DeviceModelDao deviceModelDao;
    private LoopRecyclerAdapter minePagerAdapter;
    private TextView tv_temp;
    private TextView tv_weat;
    private TextView tv_pm25;
    private TextView tv_air;
    private Context context;
    private CircleImageView circleImageView;
    private IntentFilter filter;
    private TextView tvUserName;
    private RelativeLayout rl_username;
    private TextView tv_des;
    private TextView version;

    private int BANNER_CHANGE_INTERVAL = 11100;

    private TextView btn_show_level;
    Long dayTimeStamp = 24 * 60 * 60 * 1000L;
    private String timeStamp;
    private Handler mHander;


    //声明定位回调监听器
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        filter = new IntentFilter();
        filter.addAction(LauncherMessageReceiver.ACTION_USER_UPDATE_INFO);
        deviceModelDao = new DeviceModelDao(this);
        registerReceiver(broadcastReceiver, filter);
        EventBus.getDefault().register(this);
        //导入数据
        Tools.importDatabaseRawFile(this);
        //启动服务
        ServiceUtil.startService(this);

        //更新UI信息
        UserServer.getInstance().setContext(this);
        UserServer.getInstance().userInfoUpdate();
        mHander = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        mHander.removeMessages(1);
                        mHander.sendEmptyMessageDelayed(1, BANNER_CHANGE_INTERVAL);
                        if (deviceList.size() > 1 && pager != null) {
                            try {
                                int deviceCount = deviceList.size();
                                if (deviceCount > 0) {
                                    int i = (pager.getActualCurrentPosition() + 1) % deviceCount;
                                    pager.smoothScrollToPosition(i);
                                }
                            } catch (ArithmeticException ar) {
                                //%0可能会报这个错
                                ar.printStackTrace();
                            }
                        }
                        break;
                    case 2:
                        getDeviceList();
                        mHander.removeMessages(2);
                        mHander.sendEmptyMessageDelayed(2, 2000);
                        break;
                }
            }
        };

        initView();
        List<DeviceModel> des = deviceModelDao.getDeviceListByDeviceId("06");
        if (des != null) {
            deviceList.addAll(BizUtils.parseList(deviceModelDao.getDeviceListByDeviceId("06")));
        }
        timeStamp = SharePrefenceUtil.getStringValue(getApplicationContext(), SharePrefenceUtil.SHARE_TIME_DAY);
        getLocation();
        initPager();
        //定时每天凌晨4：20分主机重新启动一次
        //setAlarm(4,testRandom1());
        setAlarm(3,30);
    }

    public void initPager() {
        if (deviceList.size() > 0) {
            try {
                LinearLayoutManager layout = new LinearLayoutManager(StartActivity.this, LinearLayoutManager.HORIZONTAL, false);
                pager.setLayoutManager(layout);
                minePagerAdapter = new LoopRecyclerAdapter(StartActivity.this, deviceList);
                pager.setAdapter(minePagerAdapter);
            }catch (Exception e){
                if (e!= null){
                    e.printStackTrace();;
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadcastReceiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        String msg = "未定义的按键!";
        if (getResources().getInteger(R.integer.wps_short_value) == event.getKeyCode()) {
            msg = "短按|WPS键!";
            Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();

            AddCmd.getInstance().blindAdd();

        } else if (getResources().getInteger(R.integer.wps_long_value) == event.getKeyCode()) {
            msg = "长按|WPS键!";
            Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }

        return super.onKeyDown(keyCode, event);
    }

    /**
     * fuc :获取天气
     * 天气接口地址
     * <a href =" https://www.heweather.com/documents/api/v5/now" > </a>
     */
    public void getWeather(final String location) {

        final String weatcher = SharePrefenceUtil.getStringValue(getApplicationContext(), SharePrefenceUtil.SHARE_KEY_WEATHER_DAY);

        if (!TextUtils.isEmpty(weatcher) && !TextUtils.isEmpty(timeStamp) && ((System.currentTimeMillis() - Long.parseLong(timeStamp)) < dayTimeStamp)) {
            WeatherModel.HeWeather5Bean h5bean = new Gson().fromJson(weatcher, WeatherModel.HeWeather5Bean.class);
            tv_weat.setText("湿度：" + h5bean.getNow().getHum());
            tv_temp.setText("温度：" + h5bean.getNow().getTmp() + " 度");
        } else {
            RetrofitFactory.getWeatherInstance().create(IpHttpService.class)
                    .getWheather(SharePrefenceUtil.getStringValue(this, SharePrefenceUtil.SHARE_WHEATHER_TOKEN), location)
                    .compose(RxJavaHelper.<WeatherModel>observerOnMainThread())
                    .subscribe(new RxSbuscriber<WeatherModel>() {
                        @Override
                        public void onSuccess(WeatherModel weatherModel) {
                            if (weatherModel != null && TextUtils.equals(weatherModel.getHeWeather5().get(0).getStatus(), "ok")) {
                                // success
                                tv_weat.setText("湿度： " + weatherModel.getHeWeather5().get(0).getNow().getHum());
                                tv_temp.setText("温度： " + weatherModel.getHeWeather5().get(0).getNow().getTmp() + " 度");
                                SharePrefenceUtil.setStringValue(getApplicationContext(), new Gson().toJson(weatherModel.getHeWeather5().get(0)), SharePrefenceUtil.SHARE_KEY_WEATHER_DAY);
                                SharePrefenceUtil.setStringValue(getApplicationContext(), String.valueOf(System.currentTimeMillis()), SharePrefenceUtil.SHARE_TIME_DAY);
                            } else {
                                Toast.makeText(StartActivity.this, "获取天气失败", Toast.LENGTH_SHORT).show();
                            }

                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Toast.makeText(StartActivity.this, "获取天气失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    /**
     * 获取传感设备
     */
    public synchronized void getDeviceList() {
        if (deviceModelDao == null) {
            return;
        }
        Observable.just(deviceModelDao.getDeviceListByDeviceId("06"))
                .map(new Func1<List<DeviceModel>, List<List<DeviceModel>>>() {
                    @Override
                    public List<List<DeviceModel>> call(List<DeviceModel> deviceModels) {
                        if (deviceModels != null)
                            deviceList.clear();
                        deviceList.addAll(BizUtils.parseList(deviceModels));
                        return deviceList;
                    }
                }).compose(RxJavaHelper.<List<List<DeviceModel>>>observerOnMainThread())
                .subscribe(new RxSbuscriber<List<List<DeviceModel>>>() {
                    @Override
                    public void onSuccess(List<List<DeviceModel>> lists) {
                        if (minePagerAdapter != null) {
                            minePagerAdapter.notifyDataSetChanged();
                        } else if (deviceList.size() > 0) {
                            initPager();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        Toast.makeText(StartActivity.this, e != null ? e.getMessage() : "获取数据错误", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    public void getPm25(final String location) {
        String pm25 = SharePrefenceUtil.getStringValue(getApplicationContext(), SharePrefenceUtil.SHARE_KEY_PM25_DAY);

        if (!TextUtils.isEmpty(pm25) && !TextUtils.isEmpty(timeStamp) && ((System.currentTimeMillis() - Long.parseLong(timeStamp)) < dayTimeStamp)) {
            Gson gson = new Gson();
            PmModel.DataBean dataBean = gson.fromJson(pm25, PmModel.DataBean.class);
            tv_pm25.setText(" PM2.5:  " + dataBean.getPm25());
            tv_air.setText(" 空气质量:  " + dataBean.getPer());
        } else {
            String addr = "";
            if (location.contains("市")) {
                addr = location.substring(0, location.length() - 1);
            }
            RetrofitFactory.getPm25Instance().create(IpHttpService.class)
                    .getPm25(addr)
                    .compose(RxJavaHelper.<PmModel>observerOnMainThread())
                    .subscribe(new RxSbuscriber<PmModel>() {
                        @Override
                        public void onSuccess(PmModel responseCallable) {
                            if (responseCallable != null && responseCallable.getData().size() > 0) {
                                PmModel.DataBean dataBean = responseCallable.getData().get(0);
                                tv_pm25.setText(" PM2.5:   " + dataBean.getPm25());
                                tv_air.setText(" 空气质量:  " + dataBean.getPer());
                                SharePrefenceUtil.setStringValue(getApplicationContext(), new Gson().toJson(dataBean), SharePrefenceUtil.SHARE_KEY_PM25_DAY);
                                SharePrefenceUtil.setStringValue(getApplicationContext(), String.valueOf(System.currentTimeMillis()), SharePrefenceUtil.SHARE_TIME_DAY);
                            } else {
                                Toast.makeText(context, "获取pm2.5数据失败", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            Toast.makeText(context, "获取pm2.5数据失败", Toast.LENGTH_SHORT).show();
                        }
                    });
        }

    }


    /**
     * 通过ip定位
     */
    public void getLocation() {

        String location = SharePrefenceUtil.getStringValue(getApplicationContext(), SharePrefenceUtil.SHARE_KEY_LOCATION_DAY);
        if (!TextUtils.isEmpty(location) && !TextUtils.isEmpty(timeStamp) && ((System.currentTimeMillis() - Long.parseLong(timeStamp)) < dayTimeStamp)) {
            address.setText(location);
            getWeather(location);
            getPm25(location);
        } else {
            RetrofitFactory.getIntance()
                    .create(IpHttpService.class)
                    .getIpLocation(SharePrefenceUtil.getStringValue(getApplicationContext(), SharePrefenceUtil.SHARE_IP_LOCATION_TOKEN))
                    .compose(RxJavaHelper.<IpLocationModel>observerOnMainThread())
                    .subscribe(new RxSbuscriber<IpLocationModel>() {
                        @Override
                        public void onSuccess(IpLocationModel ipLocationModel) {
                            if (ipLocationModel != null && TextUtils.equals("1", ipLocationModel.getStatus())) {
                                address.setText(ipLocationModel.getCity());
                                SharePrefenceUtil.setStringValue(getApplicationContext(), ipLocationModel.getCity(), SharePrefenceUtil.SHARE_KEY_LOCATION_DAY);
                                SharePrefenceUtil.setStringValue(getApplicationContext(), String.valueOf(System.currentTimeMillis()), SharePrefenceUtil.SHARE_TIME_DAY);
                                getWeather(ipLocationModel.getCity());
                                getPm25(ipLocationModel.getCity());
                            } else {
                                address.setText("定位失败");
                                Toast.makeText(StartActivity.this, ipLocationModel.getInfo(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);

                        }
                    });
        }

    }

    public void initView() {
        context = this;
        address = (TextView) findViewById(R.id.location);
        pager = (LoopRecyclerViewPager) findViewById(R.id.viewpager);
        tv_temp = (TextView) findViewById(R.id.tv_temp);
        tv_weat = (TextView) findViewById(R.id.tv_weat);
        tv_pm25 = (TextView) findViewById(R.id.tv_pm25);
        tv_air = (TextView) findViewById(R.id.tv_air);
        circleImageView = (CircleImageView) findViewById(R.id.profile_image);
        tvUserName = (TextView) findViewById(R.id.tv_username);
        rl_username = (RelativeLayout) findViewById(R.id.rl_manager_info);
        tv_des = (TextView) findViewById(R.id.tv_des);
        btn_show_level = (TextView) findViewById(R.id.btn_show_level);
        version = (TextView) findViewById(R.id.versionName);
        version.setText("版本：" + BuildConfig.VERSION_NAME);
        String des = SharePrefenceUtil.getStringValue(StartActivity.this, SharePrefenceUtil.SHAPRE_DESCRIBE_BOX);
        if (!TextUtils.isEmpty(des)) {
            tv_des.setText(des);
        }
        rl_username.setOnClickListener(this);
        boolean isShowLevel = SharePrefenceUtil.getBooleanVal(StartActivity.this, SharePrefenceUtil.SHPAE_SHOW_SENCELEL);
        if (isShowLevel) {
            btn_show_level.setText("打开");
        } else {
            btn_show_level.setText("关闭");
        }
        btn_show_level.setOnClickListener(this);

        version.setOnClickListener(this);
    }




    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_manager_info) {
            SimplePop simplePop = new SimplePop(StartActivity.this, new SimplePop.onOkCallBack() {
                @Override
                public void ok(String des) {
                    if (!TextUtils.isEmpty(des)) {
                        tv_des.setText(des);
                    }
                }
            });
            simplePop.showAtLocation(findViewById(R.id.root), Gravity.CENTER, 0, 0);
        }else  if(v.getId()==R.id.versionName){
            Log.v("StartActivity","点击了版本号");
            this.finish();
            Intent mIntent = new Intent();
            ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings");
            mIntent.setComponent(comp);
            mIntent.setAction("android.intent.action.VIEW");
            startActivity(mIntent);

        } else if (v.getId() == R.id.btn_show_level) {
            boolean isShowLevel = SharePrefenceUtil.getBooleanVal(StartActivity.this, SharePrefenceUtil.SHPAE_SHOW_SENCELEL);
            if (isShowLevel) {
                SharePrefenceUtil.setBooleanVal(StartActivity.this, false, SharePrefenceUtil.SHPAE_SHOW_SENCELEL);
                btn_show_level.setText("关闭");
            } else {
                SharePrefenceUtil.setBooleanVal(StartActivity.this, true, SharePrefenceUtil.SHPAE_SHOW_SENCELEL);
                btn_show_level.setText("打开");
            }
            if (minePagerAdapter != null) {
                minePagerAdapter.notifyDataSetChanged();
            }
        }

    }

    public static class LoopRecyclerAdapter extends RecyclerView.Adapter<LoopRecyclerAdapter.ViewHolder> {
        private List<List<DeviceModel>> list;
        private Context context;

        public LoopRecyclerAdapter(Context context, List<List<DeviceModel>> deviceList) {
            this.context = context;
            this.list = deviceList;
        }

        @Override
        public LoopRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.item_pager, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(LoopRecyclerAdapter.ViewHolder holder, int position) {

            GridViewAdapter adapter = new GridViewAdapter(context, list.get(position));
            holder.gridView.setAdapter(adapter);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            private MyPlatformGridView gridView;

            public ViewHolder(View itemView) {
                super(itemView);
                gridView = (MyPlatformGridView) itemView.findViewById(R.id.gridview);
            }
        }
    }


    public static class GridViewAdapter extends BaseAdapter {
        private List<DeviceModel> deviceModelList;
        private Context context;

        public GridViewAdapter(Context context, List<DeviceModel> deviceModelList) {
            this.deviceModelList = deviceModelList;
            this.context = context;

        }

        @Override
        public int getCount() {
            return deviceModelList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.sence_item, parent, false);
                holder.item_root = (RelativeLayout) convertView.findViewById(R.id.item_root);
                holder.title = (TextView) convertView.findViewById(R.id.deviceName);
                holder.tv_name_temp = (TextView) convertView.findViewById(R.id.level_temp);
                holder.tv_name_air = (TextView) convertView.findViewById(R.id.level_air);
                holder.tv_name_pm = (TextView) convertView.findViewById(R.id.level_pm);
                holder.tv_name_weat = (TextView) convertView.findViewById(R.id.level_weat);
                holder.tv_name_light = (TextView) convertView.findViewById(R.id.level_sunlight);
                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final DeviceModel model = deviceModelList.get(position);
            String deviceName = TextUtils.isEmpty(model.getRoomName()) ? model.getDeviceName() : model.getRoomName() + model.getDeviceName();
            holder.title.setText(deviceName);
            boolean showSenceLevel = SharePrefenceUtil.getBooleanVal(context, SharePrefenceUtil.SHPAE_SHOW_SENCELEL);
            String weatVal = "湿度：" + model.getHumidity() + "RH";
            String tmpVal = "温度：" + String.format("%.2f", model.getTemperature()) + "度";
            holder.tv_name_weat.setText(weatVal);
            holder.tv_name_temp.setText(tmpVal);
            String airVal = "空气质量：";
            String sunLightVal = "光照：";
            String pmVal = "PM2.5：";
            if (showSenceLevel) {
                airVal = airVal + BizUtils.getAirQuaLevel(String.valueOf(model.getAriQuality())) + " " + model.getAriQuality() + "";
                sunLightVal = sunLightVal + BizUtils.getSunLightLevel(String.valueOf(model.getSunLight())) + " " + model.getSunLight() + "lx";
                pmVal = pmVal + BizUtils.getPM25Level(String.valueOf(model.getPm25())) + " " + model.getPm25();
            } else {
                airVal = airVal + model.getAriQuality() + "";
                sunLightVal = sunLightVal + model.getSunLight() + "lx";
                pmVal = pmVal + String.valueOf(model.getPm25());
            }
            holder.tv_name_air.setText(airVal);
            holder.tv_name_pm.setText(pmVal);
            holder.tv_name_light.setText(sunLightVal);

            return convertView;
        }

        class ViewHolder {
            RelativeLayout item_root;
            private TextView title;
            private TextView tv_name_temp;
            private TextView tv_name_air;
            private TextView tv_name_pm;
            private TextView tv_name_weat;
            private TextView tv_name_light;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mHander.sendEmptyMessageDelayed(1, BANNER_CHANGE_INTERVAL);
        mHander.sendEmptyMessageDelayed(2, 2000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHander.removeMessages(1);
        Log.v("error_launch", "remove");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.v("error_launch", "stop---");
    }

    public void onEvent(String msg) {
        if (msg.equals(Constants.ACTION_NOTIFY_MAIN_ACTIVITY)) {
////            Log.v("error_launch","onEvent isFinish:"+isFinish);
//            if (isFinish) {
//                getDeviceList();
//                countDown();
//            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();


    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (LauncherMessageReceiver.ACTION_USER_UPDATE_INFO.equals(action)) {
                String userName = intent.getStringExtra("userName");
                if (userName != null) {
                    tvUserName.setText(userName);
                }
                String userLogoStr = intent.getStringExtra("userLogo");
                if (userLogoStr != null) {
                    if (!"".equals(userLogoStr.trim())) {
                        byte[] buffer = Base64.decode(userLogoStr, Base64.DEFAULT);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
                        circleImageView.setImageBitmap(bitmap);
                    }
                }

            }
        }


    };

    public void setAlarm(int mHour,int mMinute){
        // 获取当前时间

        Intent intent = new Intent(StartActivity.this, AlarmReceiver.class);
        PendingIntent sender = PendingIntent.getBroadcast(StartActivity.this, 0, intent, 0);

        long firstTime = SystemClock.elapsedRealtime();	// 开机之后到现在的运行时间(包括睡眠时间)
        long systemTime = System.currentTimeMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 这里时区需要设置一下，不然会有8个小时的时间差
        calendar.set(Calendar.MINUTE, mMinute);
        calendar.set(Calendar.HOUR_OF_DAY, mHour);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 选择的每天定时时间
        long selectTime = calendar.getTimeInMillis();

        // 如果当前时间大于设置的时间，那么就从第二天的设定时间开始
        if(systemTime > selectTime) {
            //Toast.makeText(StartActivity.this, "设置的时间小于当前时间", Toast.LENGTH_SHORT).show();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            selectTime = calendar.getTimeInMillis();
        }

        // 计算现在时间到设定时间的时间差
        long time = selectTime - systemTime;
        firstTime += time;

        // 进行闹铃注册
        AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
        manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, interval, sender);

        Log.i(TAG, "time ==== " + time + ", selectTime ===== " + selectTime + ", systemTime ==== " + systemTime + ", firstTime === " + firstTime);
//        Toast.makeText(StartActivity.this, "定时任务启动成功! ", Toast.LENGTH_LONG).show();
        Log.v(TAG,"定时任务启动成功!");

    }

    //生成随机数 0-59的随机数为了给每一台主机设置重启的时间分钟岔开降低服务器压力
    private int testRandom1(){
        Random random=new Random();
        return random.nextInt(60);

    }

}
